 package com.sgb.kjwl.view.ui.fragment.pick;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.sgb.kjwl.view.event.special.QuickEntryEvent;
import com.sgb.kjwl.view.ui.quickentry.BackResultContentListener;
import com.sgb.kjwl.view.ui.quickentry.QuickEntryEntity;
import com.swgk.core.util.LogUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.FragmentPickHallSceneBidingBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.pick.PickHallSceneBidListEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.sgb.link.utils.SizeUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickHallSceneBidingActivity;
import com.sgb.kjwl.view.ui.activity.pick.TenderDetailsActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.pick.PickHallSceneBidAdapter;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.widget.CommonCategoryFilterPopWindow;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.view.widget.pick.PickPopWindowView;
import com.sgb.kjwl.viewmodel.pick.PickHallSceneBidingModel;
import com.sgb.zhaocai.utils.PickCopyUtils;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 招标首页-招标大厅-现场竞标
 */
public class PickHallSceneBidingFragment extends AppFragment {

    private FragmentPickHallSceneBidingBinding binding;
    private PickHallSceneBidAdapter sceneAdapter;
    private List<PickSelectEntity> typeDatas = new ArrayList<>();
    private List<PickSelectEntity> cityDatas = new ArrayList<>();
    private List<PickSelectEntity> rundsDatas = new ArrayList<>();
    private List<PickSelectEntity> timeDatas = new ArrayList<>();
    private List<PickSelectEntity> tenderTypeDatas = new ArrayList<>();
    private List<PickSelectEntity> provinceDatas = new ArrayList<>();
    private List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> categoryDatas = new ArrayList<>();
    private List<PickSelectEntity> tabTypeList = new ArrayList<>();
    private List<PickSelectEntity> aboutDatas = new ArrayList<>();

    private PickHallBidingPopWindow typePopWindow;
    private PickHallBidingPopWindow rundsPopWindow;
    private PickHallBidingPopWindow timePopWindow;
    private ThreeLevelAreaWindow mAddressPop;
    private CommonCategoryFilterPopWindow categoryFilterPopWindow;
    private PickHallBidingPopWindow pickTabLayoutPopWindow;
    private PickHallBidingPopWindow aboutPopWindow;

    //省
    private String areacode = "";
    //招标类型
    private String tenderTypeNo = "";
    //地区
    private String citysNo = "";
    //类型
    private String typeNo = "0";
    //时间
    private String timeNo = "";
    private String timeName;
    //轮次
    private String rundsNo = "";
    private String rundsName;
    //搜索关键字
    private String searchName = "";
    //全部竞标
    private String bidType = "0";
    private String bidTypeName;
    private boolean isSearching = false;

    private int page = 1;

    private boolean isLoadMore = false;
    private boolean isChange1;
    private boolean isChange2;
    private boolean isChange3;
    private boolean isChange4;
    private boolean isChange5;
    private String goodsType;
    private String goodsTypeName;
    private int tabPosition;
    private int tabTypePosition;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private String areaName;

    @Inject
    PickHallSceneBidingModel model;
    private boolean isEnableLoadMore = false;
    private boolean isLogin = false;

    public static PickHallSceneBidingFragment newInstance() {
        PickHallSceneBidingFragment fragment = new PickHallSceneBidingFragment();
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent
                .builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_pick_hall_scene_biding, container, false);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return binding.getRoot();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {

        binding.include.tvSearchDelete.setOnClickListener(this);
        binding.include.tvSearchDelete.setVisibility(View.VISIBLE);
        binding.include.etView.setHint("搜索招标名称");
        binding.include.rightView.setOnClickListener(this);
        binding.include.rightView.setText("发布");
        binding.include.tvSearch.setOnClickListener(this);
        binding.include.tvSearch.setText("搜索");
        binding.include.ivBack.setOnClickListener(this);
        binding.surveyView.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);
        binding.ivQuickEntry.setOnClickListener(this);

        binding.include.etView.setTextColor(this.getResources().getColor(R.color.color_tab_one));
        binding.include.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.include.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (isSearching) return true;
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.include.etView.getText().toString())) {
                        MToast.showToast(getActivity(), "请输入搜索内容");
                        return true;
                    }
                    if (searchName.equals(binding.include.etView.getText().toString())){
                        MToast.showToast(getActivity(), "请输入不同的搜索内容");
                        return true;
                    }
                    isSearching = true;
                    searchName = binding.include.etView.getText().toString();
                    if (!TextUtils.isEmpty(searchName)) {
                        isSearching = false;
                        getData();
                    }
                }
                return false;
            }
        });

        binding.tvRund.setOnClickListener(this);
        binding.tvTime.setOnClickListener(this);
        binding.tvAddr.setOnClickListener(this);
        binding.tvType.setOnClickListener(this);
        //新增类别
        binding.tvCategory.setOnClickListener(this);
        binding.tvAbout.setOnClickListener(this);

        pickTabLayoutPopWindow = new PickHallBidingPopWindow(getActivity());
        pickTabLayoutPopWindow.setBgView(binding.bgPopGrayLayout);
        pickTabLayoutPopWindow.setOnResultClick((key1, key2, key3) -> {
            binding.tabLayoutType.getTabAt((int) key3).select();
            pickTabLayoutPopWindow.setDefItem((int) key3);
            goodsType = ((PickSelectEntity) key1).getNo();
            getData();
        });
        pickTabLayoutPopWindow.setOnDisMissClick(() -> {
            binding.surveyView.setImageResource(R.drawable.btn_down);
        });

        categoryFilterPopWindow = new CommonCategoryFilterPopWindow(getActivity(),false);
        categoryFilterPopWindow.setBgView(binding.bgPopGrayLayout);
        categoryFilterPopWindow.setResultListener(new CommonCategoryFilterPopWindow.Listener() {
            @Override
            public void setResultListener(String text, String result, String typeNo) {
                goodsType = result;
                goodsTypeName = text;

                if(!"全部".equals(text)){
                    updateChooseTextStatus(binding.tvCategory,1,goodsTypeName);
                    isChange4 = true;
                }else{
                    isChange4 = false;
                    updateChooseTextStatus(binding.tvCategory,0,"类别");
                }
                getData();
            }

            @Override
            public void setResetResultListener() {
                resetCategoryFilterPopWindow();
            }
        });
        categoryFilterPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChange4) {
                    updateChooseTextStatus(binding.tvCategory,0,"类别");
                } else {
                    updateChooseTextStatus(binding.tvCategory,1,goodsTypeName);
                }
            }
        });
        // 招标类型
        typePopWindow = new PickHallBidingPopWindow(getActivity());
        typePopWindow.setBgView(binding.bgPopGrayLayout);
        typePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                tenderTypeNo = ((PickSelectEntity) key1).getNo();
                String name = ((PickSelectEntity) key1).getProjectscale();

                if (!"全部".equals(name)) {
                    updateChooseTextStatus(binding.tvCategory,1,name);
                    isChange1 = true;
                } else {
                    isChange1 = false;
                    updateChooseTextStatus(binding.tvCategory,0,"招标方式");
                }
                getData();
            }
        });
        typePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChange1) {
                    updateChooseTextStatus(binding.tvCategory,0,"招标方式");
                } else {
                    updateChooseTextStatus(binding.tvCategory,1,null);
                }
            }
        });
        rundsPopWindow = new PickHallBidingPopWindow(getActivity());
        rundsPopWindow.setBgView(binding.bgPopGrayLayout);
        rundsPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                LogUtil.v("goodsInfo", "轮次类型=" + ((PickSelectEntity) type).getProjectscale());
                rundsNo = ((PickSelectEntity) type).getNo();
                rundsName = ((PickSelectEntity) type).getProjectscale();
                getData();
            }
        });

        timePopWindow = new PickHallBidingPopWindow(getActivity());
        timePopWindow.setBgView(binding.bgPopGrayLayout);
        timePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                timeNo = ((PickSelectEntity) type).getNo();
                timeName = ((PickSelectEntity) type).getProjectscale();
                if(!"全部".equals(timeName)){
                    updateChooseTextStatus(binding.tvTime,1,timeName);
                    isChange2 = true;
                }else{
                    isChange2 = false;
                    timeName = "竞标时间";
                    updateChooseTextStatus(binding.tvTime,0,timeName);
                }
                getData();
            }
        });
        timePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChange2) {
                    updateChooseTextStatus(binding.tvTime,0,timeName);
                } else {
                    updateChooseTextStatus(binding.tvTime,1,timeName);
                }
            }
        });

        aboutPopWindow = new PickHallBidingPopWindow(getActivity());
        aboutPopWindow.setBgView(binding.bgPopGrayLayout);
        aboutPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                bidTypeName = ((PickSelectEntity) type).getPickerViewText();
                bidType = ((PickSelectEntity) type).getNo();
                if("全部竞标".equals(bidTypeName)){
                    isChange5 = false;
                    bidTypeName = "全部竞标";
                    updateChooseTextStatus(binding.tvAbout,0,bidTypeName);
                    getData();
                }else{
                    if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                        jumpLogin();
                        isLogin = true;
                    } else {
                        updateChooseTextStatus(binding.tvAbout,1,bidTypeName);
                        isChange5 = true;
                        getData();
                    }
                }
            }
        });
        aboutPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    updateChooseTextStatus(binding.tvAbout,0,"全部竞标");
                }else{
                    if (!isChange5) {
                        updateChooseTextStatus(binding.tvAbout,0,bidTypeName);
                    } else {
                        updateChooseTextStatus(binding.tvAbout,1,bidTypeName);
                    }
                }
            }
        });

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tabPosition = tab.getPosition();
                if (tabPosition == 0 || tabPosition == (typeDatas.size() - 1)) {
                    binding.tvCategory.setVisibility(View.GONE);
                } else {
                    binding.tvCategory.setVisibility(View.VISIBLE);
                }
                LogUtil.v("goodsInfo", "类型=" + typeDatas.get(tab.getPosition()).getProjectscale());
                typeNo = typeDatas.get(tab.getPosition()).getNo();
                resetCategoryFilterPopWindow();
                getData();

                if (tabPosition == 0 || tabPosition == (typeDatas.size() - 1)) {
                    binding.lineTabType.setVisibility(View.GONE);
                }else{
                    tabTypeList.clear();
                    binding.tabLayoutType.setTabRippleColor(ColorStateList.valueOf(getContext().getResources().getColor(R.color.translucent)));
                    binding.tabLayoutType.removeAllTabs();
                    binding.lineTabType.setVisibility(View.VISIBLE);
                    binding.tvCategory.setVisibility(View.GONE);
                }

                if (tab != null && tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item);
                    ImageView imageView = tab.getCustomView().findViewById(R.id.image_tab_item);
                    PickCopyUtils.setImageResources(tabPosition, imageView, true,getContext());
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tabSelect.setTextColor(getResources().getColor(R.color.APPTabColor));
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item);
                    ImageView imageView = tab.getCustomView().findViewById(R.id.image_tab_item);
                    PickCopyUtils.setImageResources(tabPosition, imageView, false,getContext());
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    tabSelect.setTextColor(getResources().getColor(R.color.color_tab_one));
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        binding.tabLayoutType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tabTypePosition = tab.getPosition();
                if(tabTypePosition == 0){
                    binding.tvCategory.setVisibility(View.GONE);
                }else{
                    List<PickSelectEntity<List<PickSelectEntity>>> pickSelectEntities = categoryDatas.get(tabTypePosition).getChildren();
                    if (pickSelectEntities == null || pickSelectEntities.size() == 0) {
                        binding.tvCategory.setVisibility(View.GONE);
                    } else {
                        binding.tvCategory.setVisibility(View.VISIBLE);
                        isChange4 = false;
                        updateChooseTextStatus(binding.tvCategory,0,"类别");
                    }
                }
                goodsType = tabTypeList.get(tabTypePosition).getNo();
                getData();

                if (tab != null && tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item);
                    tabSelect.setBackgroundResource(R.drawable.search_new_blue_bg);
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tabSelect.setTextColor(getResources().getColor(R.color.APPTabColor));
                    tabSelect.invalidate();
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item);
                    tabSelect.setBackgroundResource(R.drawable.search_bg);
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    tabSelect.setTextColor(getResources().getColor(R.color.color_tab_one));
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        if (sceneAdapter == null) {
            sceneAdapter = new PickHallSceneBidAdapter(getActivity(), null);
        }
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_list_divide2));
        binding.recyclerView.addItemDecoration(divider);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(sceneAdapter);
        sceneAdapter.setOnItemClick(new AdapterOnItemClick<PickHallSceneBidListEntity>() {
            @Override
            public void onItemClick(PickHallSceneBidListEntity tenderListEntity, int position) {
                TenderDetailsActivity3.start(getActivity(), tenderListEntity.getId() + "", 0);
            }
        });
        int screenHeight = SizeUtils.getScreenHeight(getActivity());
        binding.scrollview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                RecyclerView.LayoutManager layoutManager = binding.recyclerView.getLayoutManager();
                View view = layoutManager.findViewByPosition(0);
                if (view != null){
                    int height = view.getMeasuredHeight();
                    int headHeight = screenHeight - binding.headerLayout.getHeight();
                    int gonePosition = 10 - (headHeight / view.getHeight());
                    binding.imgBackTop.setVisibility((height * gonePosition) > scrollY ? View.GONE : View.VISIBLE);
                }
            }
        });

        binding.swipeRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                page = page + 1;
                model.getList(citysNo, typeNo, timeNo, rundsNo, page, searchName, tenderTypeNo, areacode, goodsType,bidType);
                binding.swipeRefresh.finishLoadMore(300);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData();
                binding.swipeRefresh.finishRefresh(300);
            }
        });
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        binding.swipeRefresh.setScrollBoundaryDecider(new ScrollBoundaryDecider() {
            @SuppressLint("RestrictedApi")
            @Override
            public boolean canRefresh(View content) {
                if (binding.scrollview == null) return false;
                if (binding.scrollview.computeVerticalScrollOffset() == 0)
                    return true;
                return false;
            }

            @SuppressLint("RestrictedApi")
            @Override
            public boolean canLoadMore(View content) {
                if (binding.scrollview == null) return false;
                //获取recyclerView的高度
                binding.scrollview.getHeight();
                //整个View控件的高度
                int scrollRange = binding.scrollview.computeVerticalScrollRange();
                //当前屏幕之前滑过的距离
                int scrollOffset = binding.scrollview.computeVerticalScrollOffset();
                //当前屏幕显示的区域高度
                int scrollExtent = binding.scrollview.computeVerticalScrollExtent();
                int height = binding.scrollview.getHeight();
                if (height > scrollRange) {
                    return false;
                }
                if (isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent) {
                    return true;
                }
                return false;
            }
        });

        initAddressPopup();
    }


    private void initAddressPopup() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setBgView(binding.bgPopGrayLayout);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                areacode = entity.getProvinceNo();
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    areaName = entity.getProvinceName();
                    areacode = entity.getProvinceNo();
                    citysNo = "";
                    if ("0".equals(areacode)) {
                        areaName = "地区";
                    }
                    updateChooseTextStatus(binding.tvAddr, 1, areaName);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        citysNo = entity.getCityNo();
                        areaName = entity.getCityName();
                        model.getAddressCityData(scrData, citysNo);
                        updateChooseTextStatus(binding.tvAddr, 1, areaName);
                    }
                } else {
                    areaName = "地区";
                    areacode = "";
                    citysNo = "";
                    updateChooseTextStatus(binding.tvAddr, 0, areaName);
                }
                getData();
            }
        });

        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.tvAddr, "地区".equals(areaName) ? 0 : 1, areaName);
        });
    }

    private void resetCategoryFilterPopWindow() {
        goodsType = "";
        updateChooseTextStatus(binding.tvCategory,0,"类别");
        isChange4 = false;
        getCategoryAllList();
    }

    private void getCategoryAllList() {
        model.getTenderGoodsCategoryAllList(typeNo);
    }


    private void initData() {
        model.getProvinceData();
        model.getFilterTypeData();
        model.getTimesData();
        model.getTenderNewTypeList();

        String[] stringTime = new String[]{"全部竞标&0", "我发布的竞标&1", "我参与的竞标&2"};
        setAboutDatas(stringTime);
        getData();
    }

    private void getData() {
        isLoadMore = false;
        page = 1;
        model.getList(citysNo, typeNo, timeNo, rundsNo, page, searchName, tenderTypeNo, areacode, goodsType,bidType);
    }

    public void setTenderGoodsCategoryAllList(List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> datas) {
        categoryDatas.clear();
        categoryDatas.addAll(datas);
        for (int i = 0; i < categoryDatas.size(); i++) {
            PickSelectEntity pickSelectEntity = new PickSelectEntity(categoryDatas.get(i).getNo(), categoryDatas.get(i).getProjectscale());
            tabTypeList.add(pickSelectEntity);
            binding.tabLayoutType.addTab(binding.tabLayoutType.newTab().setText(pickSelectEntity.getProjectscale()));

            binding.tabLayoutType.getTabAt(i).setCustomView(R.layout.tab_item_textview_pick);

            TextView tv = binding.tabLayoutType.getTabAt(i).getCustomView().findViewById(R.id.tv_tab_item);
            if (pickSelectEntity.getProjectscale().length() > 4) {
                tv.setText(pickSelectEntity.getProjectscale().substring(0, 3) + "...");
            }else{
                if(i == 0){
                    tv.setBackgroundResource(R.drawable.search_new_blue_bg);
                    tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tv.setTextColor(getResources().getColor(R.color.APPTabColor));
                }
                tv.setText(pickSelectEntity.getProjectscale());
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.tv_rund:
                if (null != rundsDatas && rundsDatas.size() > 0) {
                    rundsPopWindow.showPopwindow(binding.roomLayout, 0, 0);
                    rundsPopWindow.setData(rundsDatas, false);
                }
                break;
            case R.id.tv_time:
                if (null != timeDatas && timeDatas.size() > 0) {
                    if(TextUtils.isEmpty(timeName)){
                        timeName = "竞标时间";
                        timePopWindow.setDefItem();
                    }
                    updateChooseTextStatus(binding.tvTime,-1,timeName);
                    timePopWindow.showPopwindow(binding.roomLayout, 0, 0);
                    timePopWindow.setData(timeDatas, false);
                }
                break;
            case R.id.tv_addr:
                if (TextUtils.isEmpty(areaName)) {
                    areaName = "地区";
                }
                updateChooseTextStatus(binding.tvAddr, TextUtils.isEmpty(areacode) && TextUtils.isEmpty(citysNo) ? -1 : -2, areaName);
                mAddressPop.showPopwindow0(binding.tvAddr);
                break;
            case R.id.tv_type:
                if (null != tenderTypeDatas && tenderTypeDatas.size() > 0) {
                    typePopWindow.showPopwindow(binding.roomLayout, 0, 0);
                    typePopWindow.setData(tenderTypeDatas, false);
                }
                break;
            case R.id.tv_category:
                if (null != categoryDatas && categoryDatas.size() > 0) {
                    if(TextUtils.isEmpty(goodsTypeName)){
                        goodsTypeName = "类别" ;
                    }
                    updateChooseTextStatus(binding.tvCategory,-1,goodsTypeName);
                    categoryFilterPopWindow.showPopWindow1(binding.tvCategory);
                    if (TextUtils.isEmpty(typeNo)) {
                        typeNo = "0";
                    }
                    categoryFilterPopWindow.setData2(categoryDatas.get(tabTypePosition).getChildren(), Integer.valueOf(typeNo), typeDatas.get(tabPosition).getProjectscale());
                }
                break;
            case R.id.right_view:
                MToast.showLongToast(getActivity(), "移动端暂不支持发布招标，请前往电脑端“经营帮/用户中心/招采 经营”发布招标信息", Gravity.CENTER);
                break;
            case R.id.tv_search:
                searchName = binding.include.etView.getText().toString();
                if (!TextUtils.isEmpty(searchName)) {
                    getData();
                }
                break;
            case R.id.tv_search_delete:
                binding.include.etView.setText("");
                searchName = "";
                getData();
                break;
            case R.id.iv_back:
                ((PickHallSceneBidingActivity) getActivity()).finish();
                break;
            case R.id.survey_view:
                binding.surveyView.setImageResource(R.drawable.btn_shop_up);
                pickTabLayoutPopWindow.showPopwindow0(binding.surveyView);
                pickTabLayoutPopWindow.setData(tabTypeList,binding.tabLayoutType.getSelectedTabPosition());
                break;
            case R.id.tv_about:
                if (null != aboutDatas && aboutDatas.size() > 0) {
                    if(TextUtils.isEmpty(bidTypeName)){
                        bidTypeName = "全部竞标";
                        aboutPopWindow.setDefItem();
                    }
                    if (isLogin && "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                        aboutPopWindow.setDefItem();
                        updateChooseTextStatus(binding.tvAbout,-1,"全部竞标");
                    }else{
                        updateChooseTextStatus(binding.tvAbout,-1,bidTypeName);
                    }
                    aboutPopWindow.setData(aboutDatas, false);
                    aboutPopWindow.showPopwindow(binding.roomLayout, 0, 0);
                }
                break;
            case R.id.img_back_top:
                binding.imgBackTop.setVisibility(View.GONE);
                binding.scrollview.smoothScrollTo(0, 0);
                binding.scrollview.scrollTo(0, 0);
                break;
            case R.id.iv_quick_entry:
                EventBus.getDefault().postSticky(new QuickEntryEvent(binding.ivQuickEntry, new BackResultContentListener() {
                    @Override
                    public boolean backResult(QuickEntryEntity entity) {
                        getActivity().finish();
                        return false;
                    }
                }));
                break;
        }
    }

    public void showList(List<PickHallSceneBidListEntity> list) {

        if (list != null){
            isEnableLoadMore = list.size() >= 10;
        }
        if (isLoadMore) {
            if (list != null && !list.isEmpty()) {
                sceneAdapter.addDatas(list);
            }
        } else {
            if (list != null && !list.isEmpty()) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                sceneAdapter.setDatas(list);
            } else {
                sceneAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void setTypeDatas(List<PickSelectEntity> datas) {
        if (datas == null) return;
        typeDatas.clear();
        typeDatas.addAll(datas);
        for (int i = 0; i < typeDatas.size(); i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab());
            binding.tabLayout.getTabAt(i).setCustomView(R.layout.tab_item_text_image_view);

            View view = binding.tabLayout.getTabAt(i).getCustomView();
            TextView tv = view.findViewById(R.id.tv_tab_item);
            ImageView imageView = view.findViewById(R.id.image_tab_item);
            if(i == 0){
                tv.setTextColor(getResources().getColor(R.color.APPTabColor));
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                PickCopyUtils.setImageResources(0, imageView, true,getContext());
            }else{
                PickCopyUtils.setImageResources(i, imageView, false,getContext());
            }
            tv.setText(typeDatas.get(i).getProjectscale());

        }

        binding.tabLayout.getTabAt(0).select();

    }

    public void setTimeDatas(List<PickSelectEntity> datas) {
        timeDatas.clear();
        datas.get(0).setCheck(true);
        timeDatas.addAll(datas);
    }

    public void setRundsDatas(List<PickSelectEntity> datas) {
        rundsDatas.clear();
        rundsDatas.addAll(datas);
    }

    public void setCityDatas(List<PickSelectEntity> data) {
        cityDatas.clear();
        cityDatas.addAll(data);
        mAddressPop.setData(scrData, false);
    }

    public void setProvinceDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(scrData, true);
        } else {
            model.getAddressCityData(scrData, citysNo);
        }
    }

    public void setTenderTypeDatas(List<PickSelectEntity> datas) {
        tenderTypeDatas.clear();
        tenderTypeDatas.addAll(datas);
    }

    public void setAboutDatas(String[] datas) {
        aboutDatas.clear();
        for (String s : datas) {
            PickSelectEntity pickSelectEntity = new PickSelectEntity();
            if (s.contains("&")) {
                String[] splitText = s.split("&");
                pickSelectEntity.setNo(splitText[1]);
                pickSelectEntity.setProjectscale(splitText[0]);
            } else {
                pickSelectEntity.setNo("");
                pickSelectEntity.setProjectscale(s);
            }
            aboutDatas.add(pickSelectEntity);
        }
    }

    /**
     * 更新选项颜色
     */
    private void updateChooseTextStatus(PickPopWindowView pickPopWindowView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.length() > 4) {
                name = name.substring(0, 4) + "...";
            }
        }
        if (value == -1 || value == -2) {
            binding.popLine.setVisibility(View.VISIBLE);
            pickPopWindowView.setChooseData(R.drawable.member_pop_blue_bg2, R.mipmap.ic_up_arrow_n, R.color.color_333333,true,name);
        }else if (value == 0) {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333,false,name);
        } else {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_new_blue_bg_10, R.mipmap.icon_down_red, R.color.color_main,false,name);
        }
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(getActivity()).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_TENDER_DETAILS_3_JUMP);
        }
    }

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(getContext()));
        //开始拉取授权页
        DialogHelper.showProgressDialog(getContext(), null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(getContext(), EventConstant.EVENT_TENDER_DETAILS_3_JUMP);
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    model.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_TENDER_DETAILS_3_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "")) && isLogin){
            updateChooseTextStatus(binding.tvAbout,1,bidTypeName);
            isChange5 = true;
            getData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ChooseAreaEvent event) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void getUrl(String url, String id) {
        WebViewX5HostActivity.start(getActivity(), url, id);
    }
}
